package model

import (
	"strings"
)

// NodeVID
// 节点：返回 vid 字段名 和 值
func NodeVID(node map[string]interface{}) (field string, vid string, ok bool) {
	for k, v := range node {
		if !isString(v) {
			continue
		}
		if endsWith(k, "id") || endsWith(k, "ID") || endsWith(k, "_id") {
			return k, v.(string), true
		}
	}
	return "", "", false
}

// EdgeInfo
// 边：返回 src, dst, rank, rand
func EdgeInfo(edge map[string]interface{}) (src, dst string, rank, rand int64) {
	for k, v := range edge {
		strVal := str(v)
		switch {
		case contains(k, "src", "from", "source"):
			src = strVal
		case contains(k, "dst", "to", "target"):
			dst = strVal
		case contains(k, "rank"):
			rank = int64(num(v))
		case contains(k, "rand"):
			rand = int64(num(v))
		}
	}
	return src, dst, rank, rand
}

// ---------- 小工具 ----------
func str(v interface{}) string {
	if s, ok := v.(string); ok {
		return s
	}
	return ""
}

func num(v interface{}) float64 {
	switch n := v.(type) {
	case float64:
		return n
	case int64:
		return float64(n)
	case int:
		return float64(n)
	default:
		return 0
	}
}

func isString(v interface{}) bool {
	_, ok := v.(string)
	return ok
}

func endsWith(s, suffix string) bool {
	return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix
}

func contains(s string, keys ...string) bool {
	ls := strings.ToLower(s)
	for _, k := range keys {
		if strings.Contains(ls, k) {
			return true
		}
	}
	return false
}
